package edu.indiana.d2i.ontology.exec;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;

import edu.indiana.d2i.ontology.AbstractSQLExec;

import edu.indiana.d2i.ontology.util.AccessDBUtil;
import edu.indiana.d2i.ontology.util.Constants;
import edu.indiana.d2i.ontology.util.OntModelUtil;

public class Forest extends AbstractSQLExec {
	private final String prefix = "forest_";
	private final String sqlPrefix = "select * from FOREST where ID=";

	public Forest(AccessDBUtil dbCon, OntModel model, int id, String objectURI) {
		super(dbCon, model, id, objectURI);
		resourceURI = Constants.NAME_SPACE + prefix + id; 	// set the URI for the resource
		sqlStatement = sqlPrefix + id;			// set SQL to get one row from DB
		individual = 							// create individual (instance)
			model.getOntClass(Constants.FOREST_CLASS).createIndividual(resourceURI);
	}

	@Override
	protected void addObjectProperties(String subjectURI) {
		ObjectProperty pHasChildRelation = model.createObjectProperty(Constants.HAS_COMPONENT);
		
		try {
			// add parent object properties
			if (subjectURI != null) {
				ObjectProperty pHasParentRelation = model.getObjectProperty(Constants.HAS_RELATIONSHIP);
				model.add(individual, pHasParentRelation, model.getIndividual(subjectURI));
			}
			
			// add child object properties
			List<Plot> childList = new ArrayList<Plot>();
			sqlStatement = "SELECT p.id from PLOT AS p where p.FK_FOREST=" + id;
			ResultSet resultSet = dbCon.query(sqlStatement);
			while (resultSet.next()) {
				int plotID = resultSet.getInt("id");
				
				// actually add the object properties
				Plot plot = new Plot(dbCon, model, plotID, resourceURI);
				childList.add(plot);
				model.add(individual, pHasChildRelation, plot.getIndividual());
			}
			
			for (Plot plot : childList) {
				plot.setData2JenaModel();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/* test driver */
	public static void main(String[] args) {
		AccessDBUtil dbCon = new AccessDBUtil("IFRIDB", "", "");
		com.hp.hpl.jena.ontology.OntModel model = OntModelUtil.createOntModel();
		
		dbCon.openConnection();
		int id = 1;
		AbstractSQLExec forest1 = new Forest(dbCon, model, id, null);
		forest1.setData2JenaModel();
		id = 2;
		AbstractSQLExec forest2 = new Forest(dbCon, model, id, null);
		forest2.setData2JenaModel();
		
		try {
			FileWriter fstream = new FileWriter("out.owl");
			model.write(fstream, "RDF/XML");
			dbCon.closeConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
